<?php

namespace app\upload\model;

use app\admin\model\Common;

class File extends Common
{
    protected $dateFormat = 'Y-m-d H:i:S';
    protected $type = [
        'create_time' => 'timestamp',
        'update_time' => 'timestamp',
    ];
    protected $autoWriteTimestamp = true;

    /**
     * 文件上传
     * @param file   $file     文件
     * @param array  $setting  文件上传配置
     * @param string $path_key 返回图片路径的下标
     * @return bool
     * @throws \Exception
     */
    public function upload($file, $setting, $path_key = 'path')
    {
        /* 上传文件 */
        $fileObj = request()->file(array_keys($file)[0]);
        if (!empty($fileObj)) {
            $hash['md5'] = $fileObj->hash('md5');
            $hash['sha1'] = $fileObj->hash('sha1');

            $is_have = $this->isFile($hash);
            if ($is_have) {
                $id = $is_have;
            } else {
                $infoObj = $fileObj->validate(['size' => $setting['size'], 'ext' => $setting['ext']])->rule($setting['rule'])->move($setting['rootPath'], true, $setting['replace']);
                if ($infoObj) {
                    $this->data = [
                        'path' => "/uploads/File/" . str_replace('\\', '/', $infoObj->getSaveName()),
                        'md5' => $hash['md5'],
                        'sha1' => $hash['sha1'],
                    ];

                    $this->save();
                    $id = $this->id;
                } else {
                    $this->error = $fileObj->getError();
                    return false;
                }
            }

            $info = $this->field("id,path " . $path_key)->where(["id" => $id])->find();

            return $info; //文件上传成功
        } else {
            $this->error = '没有文件上传';
            return false;
        }

    }

    /**
     * 检测当前上传的文件是否已经存在
     * @param array $file 文件上传数组
     * @return boolean       文件信息， false - 不存在该文件
     * @throws Exception
     */
    public function isFile($file)
    {
        if (empty($file['md5'])) {
            throw new Exception('缺少参数:md5');
        }
        /* 查找文件 */
        $map = array('md5' => $file['md5'], 'sha1' => $file['sha1'],);
        return $this->field(true)->where($map)->value("id");
    }

    /**
     * 获取最后一次上传错误信息
     * @return string 错误信息
     */
    public function getError()
    {
        return $this->error;
    }
}